package com.android.support.lib.universal.load;

import java.util.HashMap;
import java.util.Map;

import com.android.support.lib.universal.R;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.Notification.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * 需要注册， <service
 * android:name="com.android.support.lib.universal.load.LoadService" ></service>
 * 
 * @author 彭治铭
 *
 */
@SuppressLint("UseSparseArrays")
public class LoadService extends Service {
	private NotificationManager manager;
	private Map<String, Notification> notificationMap = new HashMap<String, Notification>();
	private Notification notification;// 通知
	// 下载（包括暂停继续）
	private final String LOAD = "LOAD";
	// 取消下载
	private final String CANCEL = "CANCEL";

	LoadUtil loadUtil = new LoadUtil();

	@Override
	public void onCreate() {
		super.onCreate();
		manager = (NotificationManager) getApplicationContext()
				.getSystemService(getApplicationContext().NOTIFICATION_SERVICE);

	}

	@SuppressLint("NewApi")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Bundle bundle = intent.getExtras();
		// 唯一标示(虽然是字符串类型，但是必须是纯数字，以便转化为int类型)
		String id = bundle.getString("id");
		String url = bundle.getString("url");
		// 文件名，必须带后缀
		String fileName = bundle.getString("fileName", null);
		sendNotificationView(id, url, fileName);
		return START_REDELIVER_INTENT;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * 更新通知栏UI
	 */
	Handler uiHander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			String id = msg.getData().getString("id");
			Load load = loadUtil.loadMap.get(id);
			notification = notificationMap.get(id);
			// 获取notification的RemoteViews布局
			RemoteViews remoteViews = notification.contentView;
			if (load.getSpeed() != null) {
				// 下载速度
				remoteViews.setTextViewText(R.id.txtSpeech, load.getSpeed());
			}
			if (load.getCurrent() != null) {
				// 文件当前大小
				remoteViews.setTextViewText(R.id.txtCurrent, load.getCurrent());
			}
			if (load.getTatal() != null) {
				// 文件总大小
				remoteViews.setTextViewText(R.id.txtTatal,
						" / " + load.getTatal());
			}
			switch (msg.what) {
			case LoadState.LINEUP:// 排队等待中
				// 下载速度（目前显示状态）
				remoteViews.setTextViewText(R.id.txtSpeech, load.getState());
				// 更新notification的RemoteViews布局
				manager.notify(Integer.valueOf(load.getId()), notification);

				break;
			case LoadState.DOWNLOAD:// 下载中
				if (load.getProgress() != null) {
					// 进度
					remoteViews.setTextViewText(R.id.txtPercent,
							load.getProgress());
				}
				// 进度条
				remoteViews.setProgressBar(R.id.down_progress,
						(int) load.getByteTotal(), (int) load.getByteCurrent(),
						false);
				// 按钮状态
				remoteViews.setImageViewResource(R.id.btnLoad,
						R.drawable.lib_btn_load_stop);
				// 更新notification的RemoteViews布局
				manager.notify(Integer.valueOf(load.getId()), notification);
				break;
			case LoadState.PAUSE:// 已暂停
				// 下载速度（目前显示状态）
				remoteViews.setTextViewText(R.id.txtSpeech, load.getState());
				// 按钮状态
				remoteViews.setImageViewResource(R.id.btnLoad,
						R.drawable.lib_btn_load_play);
				// 更新notification的RemoteViews布局
				manager.notify(Integer.valueOf(load.getId()), notification);
				break;
			case LoadState.COMPLETE:// 完成
				// 去除通知
				manager.cancel(Integer.valueOf(id));
				break;
			case LoadState.FAILURE:// 失败
				// 去除通知
				manager.cancel(Integer.valueOf(id));
				String name = "";
				if (load != null) {
					name = load.getName();
				}
				Toast.makeText(getApplicationContext(), "亲，" + name + "下载失败鸟。",
						Toast.LENGTH_LONG).show();
				break;
			}
		}
	};
	/**
	 * 广播，执行方法
	 */
	BroadcastReceiver onClickReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			String NotificationId = intent.getExtras().getString(
					"NotificationId");
			if (intent.getAction().equals(LOAD)) {// 下载
				load(NotificationId);
			}
			if (intent.getAction().equals(CANCEL)) {// 取消下载
				cancel(NotificationId);
			}
		}
	};

	/**
	 * 发送通知
	 */
	@SuppressLint("NewApi")
	public Object sendNotificationView(String id, String url, String fileName) {
		Load reload = loadUtil.loadMap.get(id);
		if (reload != null) {
			// 防止线程错乱
			if (!reload.reLoad()) {
				// 不需要重新下载，不做任何处理
				return null;
			}
		}
		Load load = loadUtil.loadFile(getApplicationContext(), id, url,
				fileName, null, null, null, null, null, null, LoadState.IMG,
				uiHander, null);
		Builder builder = new Builder(getApplicationContext());
		/**
		 * setSmallIcon状态栏里的图标，下拉表里最右边的图标(也是通知一开始所显示的提示图标)。必不可少，不然通知无反应！
		 */
		builder.setSmallIcon(R.drawable.lib_btn_load_ring);
		/**
		 * setContent自定义视图覆盖系统默认的，以上的设置都将无效
		 */
		RemoteViews remoteViews = new RemoteViews(getApplicationContext()
				.getPackageName(), R.layout.lib_service_load);
		// 文件名
		remoteViews.setTextViewText(R.id.txtName, load.getName());
		builder.setContent(remoteViews);
		Intent notificationIntent = new Intent(getApplicationContext(),
				LoadService.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, notificationIntent, 0);
		builder.setContentIntent(pendingIntent);
		// 注册
		IntentFilter filter = new IntentFilter();
		filter.addAction(LOAD);// 添加具有该标识的intent,即监测具有该标识的intent
		filter.addAction(CANCEL);
		registerReceiver(onClickReceiver, filter);

		Intent LOADClick = new Intent(LOAD);// 对Intetn进行标示
		LOADClick.putExtra("NotificationId", load.getId());

		PendingIntent LOADClickIntent = PendingIntent.getBroadcast(
				this,// 参数二，标示该广播的ID,两个Broadcast的ID必须不一样。否则传数据时，后面的Intent会覆盖前一个Intent的值
				Integer.valueOf(load.getId()), LOADClick,
				PendingIntent.FLAG_UPDATE_CURRENT);// PendingIntent.FLAG_UPDATE_CURRENT
													// 数据实时更新
		remoteViews.setOnClickPendingIntent(R.id.btnLoad, LOADClickIntent);

		Intent CANCELClick = new Intent(CANCEL);
		CANCELClick.putExtra("NotificationId", load.getId());
		PendingIntent CANCELClickIntent = PendingIntent.getBroadcast(this,
				Integer.valueOf(load.getId()), CANCELClick, 0);
		remoteViews
				.setOnClickPendingIntent(R.id.down_cancel, CANCELClickIntent);
		notification = builder.build();

		// notification.flags = Notification.FLAG_NO_CLEAR;
		// 用户无法清除,必须在builder.build()之后，不然无效

		notificationMap.put(load.getId(), notification);
		manager.notify(Integer.valueOf(load.getId()), notification);
		sendBroadcast(LOADClick);// 发送广播，下载
		return null;
	}

	/**
	 * 下载
	 */
	public void load(String NotificationId) {
		Load load = loadUtil.loadMap.get(NotificationId);
		if (load != null) {
			load.loadListener();
		}
	}

	/**
	 * 取消下载
	 */
	public void cancel(String NotificationId) {
		Load load = loadUtil.loadMap.get(NotificationId);
		if (load != null) {
			if (load.getHandler() != null) {
				load.getHandler().cancel();
				;
			}
		}
		// 去除通知
		manager.cancel(Integer.valueOf(NotificationId));
	}

}
